package com.yc.hwc.web;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.yc.hwc.bean.Comment;
import com.yc.hwc.bean.Result;
import com.yc.hwc.bean.Task;
import com.yc.hwc.bean.TaskLog;
import com.yc.hwc.bean.User;
import com.yc.jpa.bean.PageBean;
import com.yc.util.Utils;

@Controller
@RequestMapping(path = { "hwcindex", "/" })
public class IndexDo {

	@Resource
	private UserDo iud;

	@Resource
	private TaskDo itd;

	@Resource
	private TaskLogDo itld;

	@Resource
	private CommentDo cd;

	@GetMapping
	String index() {
		return "index";
	}

	@GetMapping("/go_{page}")
	String topage(@PathVariable String page) {
		return "back/" + page;
	}

	@GetMapping("/to_{page}")
	String topage(@PathVariable String page, HttpServletRequest request) {
		if ("login".equals(page) && request.getSession().getAttribute("savedUri") == null) {
			String path = request.getHeader("Referer");
			// 登录请求不保存
			if (mustSave(path)) {
				if (request.getParameter("todo") != null) {
					if (!path.contains("?"))
						path += "?";
					path += "&todo=" + request.getParameter("todo");
				}
				request.getSession().setAttribute("savedUri", path);
			}
		}
		/*
		 * URL url = getClass().getClassLoader().getResource("templates"); File root =
		 * new File(url.toString().replace(url.getProtocol() + ":/", "")); File file =
		 * findFile(root, page); String path = file.toString().replace(root.toString(),
		 * "").replace(".html", ""); return path.replaceAll("\\\\", "/");
		 */
		return page;
	}

	private boolean mustSave(String path) {
		return path!=null && !"login".equals(path) && !path.startsWith("http");
	}

	/*
	 * private File findFile(File dir, String page) { File[] fs = dir.listFiles(new
	 * FilenameFilter() {
	 * 
	 * @Override public boolean accept(File dir, String name) { return
	 * name.equalsIgnoreCase(page + ".html"); } }); if (fs.length > 0) { return
	 * fs[0]; } else { fs = dir.listFiles(new FileFilter() {
	 * 
	 * @Override public boolean accept(File pathname) { return
	 * pathname.isDirectory(); } }); for (File f : fs) { File ret = findFile(f,
	 * page); if (ret != null) { return ret; } } return null; } }
	 */

	@PostMapping("login")
	@ResponseBody
	Result<?> login(@Valid User user, Errors errors, HttpSession session, HttpServletResponse resp) {
		Result<?> res = iud.login(user, errors, session);
		if (res.getCode() == 1) {
			User dbuser = (User) session.getAttribute("loginedUser");
			Cookie c = new Cookie("KYRBOGHFHNK", dbuser.getId() + "");
			c.setHttpOnly(true);
			c.setMaxAge(60 * 60 * 24 * 7);// 一周之内免登陆
			resp.addCookie(c);
		}
		return res;
	}

	@PostMapping("setpwd")
	@ResponseBody
	Result<?> setpwd(User user, @SessionAttribute User loginedUser) {
		if (loginedUser.getPwd().equals(user.getPwd()) == false) {
			return Result.failure("原密码错误！");
		}
		if (user.getClsSn().matches(".{6,12}") == false) {
			return Result.failure("新密码长度必须是6~12位！");
		}
		if (user.getClsSn().equals(user.getHead()) == false) {
			return Result.failure("确认密码与新密码不一致！");
		}
		String oldpwd = loginedUser.getPwd();
		loginedUser.setPwd(user.getClsSn());
		if(Utils.isEmpty(user.getEmail())==false) {
			loginedUser.setEmail(user.getEmail());
		}
		Result<?> ret = iud.save(loginedUser, null);
		if (ret.getCode() == 1) {
			return Result.success("密码修改成功！");
		} else {
			loginedUser.setPwd(oldpwd);
			return ret;
		}
	}

	@GetMapping("myTaskLog")
	@ResponseBody
	List<TaskLog> myTaskLog(@SessionAttribute User loginedUser, TaskLog tasklog) {
		Utils.setBean(tasklog, "inUser.id", loginedUser.getId());
		return itld.find(tasklog, PageBean.defaultPage()).getContent();
	}

	@PostMapping("commit")
	@ResponseBody
	Result<?> commit(@Valid TaskLog tl, Errors errors, @SessionAttribute User loginedUser) {
		tl.setInUser(loginedUser);
		return itld.save(tl, errors);
	}

	@PostMapping("reply")
	@ResponseBody
	Result<?> reply(@Valid Comment cmt, Errors errors, @SessionAttribute(required = false) User loginedUser) {
		cmt.setInUser(loginedUser);
		return cd.save(cmt, errors);
	}

	@RequestMapping("logout")
	String logout(HttpSession session, HttpServletResponse resp) {
		session.invalidate();
		Cookie c = new Cookie("KYRBOGHFHNK", "0");
		c.setHttpOnly(true);
		c.setMaxAge(0);// 一周之内免登陆
		resp.addCookie(c);
		return "redirect:" + this.buildRedirectPath("/");
	}

	@RequestMapping("getLoginedUser")
	@ResponseBody
	User getLoginedUser(@SessionAttribute(required = false) User loginedUser) {
		return loginedUser;
	}

	@RequestMapping("task/save")
	@ResponseBody
	Result<?> saveTask(@Valid Task task, Errors errors, @SessionAttribute(required = false) User loginedUser) {
		if (loginedUser != null) {
			task.setInUser(loginedUser);
		}
		return itd.save(task, errors);
	}

	@GetMapping("continue")
	String toContinue(HttpSession session) {
		String savedUri = (String) session.getAttribute("savedUri");
		if (savedUri == null) {
			savedUri = buildRedirectPath("/");
		} else {
			session.removeAttribute("savedUri");
			savedUri = buildRedirectPath(savedUri);
		}
		return "redirect:" + savedUri;
	}

	@RequestMapping("getTaskLog")
	@ResponseBody
	TaskLog getTaskLog(TaskLog taskLog, @SessionAttribute(required = false) User loginedUser) {
		if (loginedUser == null) {
			return new TaskLog();
		} else {
			Utils.setBean(taskLog, "inUser.id", loginedUser.getId());
			Page<TaskLog> page = itld.find(taskLog, PageBean.defaultPage());
			return page.isEmpty() ? new TaskLog() : page.getContent().get(0);
		}

	}

	@Value("${zuul.host}")
	private String host;
	@Value("${zuul.post}")
	private int post;

	public String buildRedirectPath(String path) {
		return path = path.startsWith("http") ? path : String.format("http://%s:%s" + path, host, post);
	}

}
